part of flutter_project_tool;

void updateAndroidInfo(ArgResults options, Map<String, dynamic> config) {
  final androidConfig = config['android'][options['platform']];
  updateManifest(androidConfig);
  updateBuildGradle(config, androidConfig);
}

void updateManifest(YamlMap config) {
  String androidAppName = config['name'];
  print('-------------Android--------------');
  print('显示名：$androidAppName');
  print('版本号：${config['version']}');
  print('----------------------------------');
  final file = File(_kAndroidManifestPath);
  final stringValue = file.readAsStringSync();
  final document = XmlDocument.parse(stringValue);
  final manifest = document.getElement('manifest')!;
  final application = manifest.getElement('application')!;
  application.setAttribute('android:label', androidAppName);
  var elementFound = true;
  final umengElement = application.children.firstWhere((e) {
    return e.nodeType == XmlNodeType.ELEMENT &&
        (e as XmlElement).name.local == 'meta-data' &&
        e.getAttribute('android:name') == 'UMENG_APPKEY';
  }, orElse: () {
    application.children.add(XmlElement(
      XmlName('meta-data'),
      [
        XmlAttribute(XmlName('android:name'), 'UMENG_APPKEY'),
        XmlAttribute(XmlName('android:value'), config['umeng_key'])
      ],
      [],
    ));
    elementFound = false;
    return XmlElement(XmlName(''));
  });
  if (elementFound) {
    umengElement.setAttribute('android:value', config['umeng_key']);
  }
  file.writeAsStringSync(document.toXmlString(pretty: true, indent: '    '));
  print('android 更新manifest完成');
}

void updateBuildGradle(Map<String, dynamic> config, YamlMap androidConfig) {
  final file = File(_kAndroidBuildGradlePath);
  String version = androidConfig['version'];
  final versionCode = version.replaceAll('.', '');
  var stringValue = file
      .readAsStringSync()
      .replaceAll(
        RegExp('applicationId .*'),
        'applicationId \'${androidConfig['application_id']}\'',
      )
      .replaceAll(
        RegExp('versionCode .*'),
        'versionCode $versionCode',
      )
      .replaceAll(
        RegExp('versionName .*'),
        'versionName \'$version\'',
      );
  stringValue = stringValue
      .replaceFirstMapped(RegExp(r'manifestPlaceholders[\s\S]*\]'), (match) {
    var manifestPlaceholders = match.input.substring(match.start, match.end);
    if (manifestPlaceholders.contains('TENCENT_APP_ID')) {
      manifestPlaceholders = manifestPlaceholders.replaceFirst(
          RegExp('TENCENT_APP_ID:.*'),
          'TENCENT_APP_ID: \'${config['qq_app_id']}\',');
    } else {
      final index = manifestPlaceholders.indexOf('[') + 1;
      manifestPlaceholders = manifestPlaceholders.substring(0, index) +
          '\n            TENCENT_APP_ID: \'${config['qq_app_id']}\',' +
          manifestPlaceholders.substring(index, manifestPlaceholders.length);
    }
    if (manifestPlaceholders.contains('JPUSH_APPKEY')) {
      manifestPlaceholders = manifestPlaceholders.replaceFirst(
          RegExp('JPUSH_APPKEY:.*'),
          'JPUSH_APPKEY: \'${config['jpush_key']}\',');
    } else {
      final index = manifestPlaceholders.indexOf('[') + 1;
      manifestPlaceholders = manifestPlaceholders.substring(0, index) +
          '\n            JPUSH_PKGNAME: applicationId,' +
          '\n            JPUSH_CHANNEL: \'developer-default\',' +
          '\n            JPUSH_APPKEY: \'${config['jpush_key']}\',' +
          manifestPlaceholders.substring(index, manifestPlaceholders.length);
    }
    return manifestPlaceholders;
  });
  file.writeAsStringSync(stringValue);
  print('android 更新build gradle完成');
}
